﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
using Newtonsoft.Json.Linq;

using CanDoo;
using CanDoo.Core;
using CanDoo.Data;
using CanDoo.Web;
using CanDoo.FineUI;
using CanDoo.Extensions;
using CanDoo.Core.Context;
using CanDoo.Oil.Core.Models;
using CanDoo.Oil.Core.DTOs;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Admin.Core.Contracts;
using FineUIPro;

namespace CanDoo.Oil.WebApp.buyInOrder
{
    public partial class Edit : EditPagebase<IInOrderContract, InOrder>
    {
        public ISupplierContract SupplierContract { get; set; }
        public IWarehouseContract WarehouseContract { get; set; }
        public IInOrderDetailContract InOrderDetailContract { get; set; }
        public IUserContract UserContract { get; set; }
        public IOperator Operator { get; set; }
        private bool AppendToEnd = true;
        private int ShowRowCount = 10;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //FineUIListHelper.BindDDL<Supplier>(SupplierContract.GetResolvedTree(), 0L, ed_Supplier,true);
                //FineUIListHelper.BindDDL(SupplierContract.EntityName, this.SupplierContract.GetSelectList(), 0L, ed_Supplier,true);
                //FineUIListHelper.BindDDL<Warehouse>(WarehouseContract.GetResolvedTree(), 0L, ed_Warehouse,true);
                //FineUIListHelper.BindDDL(WarehouseContract.EntityName, this.WarehouseContract.GetSelectList(), 0L, ed_Warehouse,true);
                //FineUIListHelper.BindDDL<User>(UserContract.GetResolvedTree(), 0L, ed_User,true);
                //FineUIListHelper.BindDDL(UserContract.EntityName, this.UserContract.GetSelectList(), 0L, ed_User,true);
                if (PageMode != pagemode.Add)
                    LoadData();
                else
                { 
                    ed_OrderDate.SetValue(DateTime.Now.TimeToStringDate());
                    ed_User.Value = Operator.UserId.ToString();
                    ed_User.Text = Operator.Name;
                }
                #region 表格编辑  Page_Load

                DB.KeepReading(() =>
                {
                    var ChildList = new List<InOrderDetail>();
                    if (PageMode != pagemode.Add)
                    {
                        var m = Manager.GetById(EntityId);
                        if (m != null)
                            ChildList = m.InOrderDetails.ToList();
                    }
                    BindChild(ChildList);
                });

                #endregion
            }
        }

        protected override void PagePowerCheck()
        {
            base.PagePowerCheck();
            if (PageMode == pagemode.Update && this.EnableEdit)
            {
                var PowerEntity = Manager.GetById(EntityId);
                this.EnableEdit = this.EnableEdit && PowerEntity.PassState == CanDoo.Core.Data.PassState.Wait;//&& !PowerEntity.IsDeleted;
            }
        }

        #region 表格编辑
        private void BindChild(List<InOrderDetail> childList)
        {
            var GridData = EntityChange(childList);
            GridChild.DataSource = GridData;
            GridChild.DataBind();
        }

        private List<ProductItem> EntityChange(List<InOrderDetail> childList)
        {
            var productItemList = new List<ProductItem>();
            if (childList != null)
            {
                foreach (var m in childList)
                {
                    productItemList.Add(Manager.EntityChange(m));
                }
            }
            for (int i = productItemList.Count; i < ShowRowCount; i++)
            {
                var m = new ProductItem();
                m.Id = 0L;
                productItemList.Add(m);
            }
            return productItemList;
        }

        private OperationResult SaveChild(InOrder Entity)
        {
            if (Entity.InOrderDetails == null)
                Entity.InOrderDetails = new List<InOrderDetail>();
            var mEntities = Entity.InOrderDetails;
            // 修改的现有数据
            Dictionary<int, Dictionary<string, object>> modifiedDict = GridChild.GetModifiedDict();
            foreach (int rowIndex in modifiedDict.Keys)
            {
                var rowID = GridChild.DataKeys[rowIndex][0].ToLong();
                if (rowID >  0L)
                {
                    var mEntity = mEntities.FirstOrDefault(p => p.Id == rowID);
                    UpdateDataRow(modifiedDict[rowIndex], mEntity);
                }
                else
                {
                    InOrderDetail mEntity = new InOrderDetail();
                    mEntity.Id = IdMaker.NewId();
                    mEntity = UpdateDataRow(modifiedDict[rowIndex], mEntity);
                    mEntities.Add(mEntity);
                }
            }

            // 删除现有数据
            List<int> deletedRows = GridChild.GetDeletedList();
            foreach (int rowIndex in deletedRows)
            {
                var rowID = GridChild.DataKeys[rowIndex][0].ToLong();
                if (rowID >  0L)
                {
                    var item = mEntities.FirstOrDefault(p => p.Id == rowID);
                    if (item != null)
                    {
                        mEntities.Remove(item);
                        InOrderDetailContract.Delete(item);
                    }
                }
            }

            // 新增数据
            List<Dictionary<string, object>> newAddedList = GridChild.GetNewAddedList();

            if (AppendToEnd)
            {
                for (int i = 0; i < newAddedList.Count; i++)
                {
                    InOrderDetail mEntity = new InOrderDetail();
                    mEntity.Id = IdMaker.NewId();
                    mEntity = UpdateDataRow(newAddedList[i], mEntity);
                    mEntities.Add(mEntity);
                }
            }
            else
            {
                for (int i = newAddedList.Count - 1; i >= 0; i--)
                {
                    InOrderDetail mEntity = new InOrderDetail();
                    mEntity.Id = IdMaker.NewId();
                    mEntity = UpdateDataRow(newAddedList[i], mEntity);
                    mEntities.Add(mEntity);
                }
            }
            return new OperationResult(OperationResultType.Success);
        }

        private InOrderDetail UpdateDataRow(Dictionary<string, object> rowDict, InOrderDetail mEntity)
        {
            if (rowDict.ContainsKey("ProductId"))
            {
                if (rowDict["ProductId"] != null && rowDict["ProductId"].ToLong() >  0L)
                    mEntity.ProductId = rowDict["ProductId"].ToLong();
                else
                    throw new Exception("产品参数错误");
            }
            if (rowDict.ContainsKey("Price"))
            {
                if (rowDict["Price"] != null && !rowDict["Price"].ToString().IsEmpty())
                    mEntity.Price = rowDict["Price"].ToDouble();
                else
                    throw new Exception("请检查单价是否填写完整");
            }
            if (rowDict.ContainsKey("Num"))
            {
                if (rowDict["Num"] != null && !rowDict["Num"].ToString().IsEmpty())
                    mEntity.Num = rowDict["Num"].ToDouble();
                else
                    throw new Exception("请检查数量是否填写完整");
            }
            if (rowDict.ContainsKey("Money"))
            {
                if (rowDict["Money"] != null && !rowDict["Money"].ToString().IsEmpty())
                    mEntity.Money = rowDict["Money"].ToDouble();
                else
                    throw new Exception("请检查金额是否填写完整");
            }
            if (rowDict.ContainsKey("Remark"))
            {
                if (rowDict["Remark"] != null)
                    mEntity.Remark = rowDict["Remark"].ToString();
            }

            if(mEntity.Price <= 0)
                throw new Exception("单价不允许小于等于0");
            if (mEntity.Num <= 0)
                throw new Exception("数量不允许小于等于0");
            if (mEntity.Money <= 0)
                throw new Exception("金额不允许小于等于0");

            mEntity.Coefficient = 1;
            return mEntity;
        }
        #endregion
        protected override void LoadData(InOrder entity)
        {
            ed_barcode.ImageUrl = "/barcode.aspx?barcode=" + entity.Code;

            ed_Code.SetValue(entity.Code);
            ed_OrderDate.SetValue(entity.OrderDate);
            ed_RequestDate.SetValue(entity.RequestDate);
            if (entity.Supplier != null)
            {
                ed_Supplier.Values = new string[] { entity.Supplier.Id.ToString() };
                ed_Supplier.Text = entity.Supplier.Name;
            }
            if (entity.Warehouse != null)
            {
                ed_Warehouse.Values = new string[] { entity.Warehouse.Id.ToString() };
                ed_Warehouse.Text = entity.Warehouse.Name;
            }
            if (entity.User != null)
            {
                ed_User.Values = new string[] { entity.User.Id.ToString() };
                ed_User.Text = entity.User.Name;
            }
            ed_Num.SetValue(entity.Num);
            ed_Money.SetValue(entity.Money);
            ed_PaymentDays.SetValue(entity.PaymentDays);
            ed_AppointPayDate.SetValue(entity.AppointPayDate);
            ed_Remark.SetValue(entity.Remark);
        }

        protected override OperationResult SaveData(InOrder entity)
        {
            if(PageMode==pagemode.Add)
            {
                entity.Code = Manager.GetNewCode();
                entity.Name = entity.Code;
            }
            entity.OrderDate = ed_OrderDate.GetValue().ToNullableDateTime();
            if (entity.OrderDate == DateTime.MinValue)
                entity.OrderDate = null;
            entity.RequestDate = ed_RequestDate.GetValue().ToNullableDateTime();
            if (entity.RequestDate == DateTime.MinValue)
                entity.RequestDate = null;
            if (ed_Supplier.Values.Count() > 0 && ed_Supplier.Values[0].ToLong() >  0L)
                entity.SupplierId = ed_Supplier.Values[0].ToLong();
            else
                entity.SupplierId = 0L;
            if (ed_Warehouse.Values.Count() > 0 && ed_Warehouse.Values[0].ToLong() >  0L)
                entity.WarehouseId = ed_Warehouse.Values[0].ToLong();
            else
                entity.WarehouseId = 0L;
            if (ed_User.Values.Count() > 0 && ed_User.Values[0].ToLong() >  0L)
                entity.UserId = ed_User.Values[0].ToLong();
            else
                entity.UserId = 0L;
            if (PageMode == pagemode.Add)
            {
                entity.Status = 1;
                entity.AlreadyNum = 0;
                entity.AlreadyMoney = 0;
            }
            entity.Num = ed_Num.GetValue().ToDouble();
            entity.Money = ed_Money.GetValue().ToDouble();
            entity.PaymentDays = ed_PaymentDays.GetValue().ToInt();
            entity.AppointPayDate = ed_AppointPayDate.GetValue().ToNullableDateTime();
            if (entity.AppointPayDate == DateTime.MinValue)
                entity.AppointPayDate = null;
            entity.Remark = ed_Remark.GetValue().ToString();
            SaveChild(entity);
            return base.SaveData(entity);

        }

        protected void WindowSearch_Close(object sender, WindowCloseEventArgs e)
        {
            if (!String.IsNullOrEmpty(e.CloseArgument))
            {
                JObject dataObj = null;

                try
                {
                    dataObj = JObject.Parse(e.CloseArgument);
                }
                catch (Exception)
                {
                    // nothing
                }

                if (dataObj != null)
                {
                    string rowid = dataObj.Value<string>("rowid");
                    string ProductId = dataObj.Value<string>("ProductId");
                    string Code = dataObj.Value<string>("Code");
                    string Name = dataObj.Value<string>("Name");
                    string SN = dataObj.Value<string>("SN");
                    string Model = dataObj.Value<string>("Model");
                    string Specifications = dataObj.Value<string>("Specifications");
                    string Unit = dataObj.Value<string>("Unit");
                    string Price = dataObj.Value<string>("Price");

                    JObject columnValues = new JObject();
                    columnValues.Add("ProductId", ProductId);
                    columnValues.Add("Code", Code);
                    columnValues.Add("Name", Name);
                    columnValues.Add("SN", SN);
                    columnValues.Add("Model", Model);
                    columnValues.Add("Specifications", Specifications);
                    columnValues.Add("Unit", Unit);
                    columnValues.Add("Price", Price);
                    columnValues.Add("Num", "0");
                    columnValues.Add("Money", "0");
                    columnValues.Add("ChangeNum", "0");
                    columnValues.Add("ChangeMoney", "0");

                    // cancelEdit用来取消编辑
                    string updateCellScript = String.Format("F('{0}').cancelEdit();F('{0}').updateCellValue('{1}',{2});", GridChild.ClientID, rowid, columnValues);

                    PageContext.RegisterStartupScript(updateCellScript);


                    //PageContext.RegisterStartupScript(sb.ToString());

                }
            }
        }

        protected void ed_Name_TriggerClick(object sender, EventArgs e)
        {
            string[] selectedCell = GridChild.SelectedCell;
            if (selectedCell != null)
            {
                PageContext.RegisterStartupScript(WindowSearch.GetShowReference("../selectSearch/SearchProduct.aspx?rowid=" + selectedCell[0]));
            }
        }

        protected void ed_Supplier_TextChanged(object sender, EventArgs e)
        {
            if (ed_Supplier.Value != "" && ed_Supplier.Value.ToLong() >  0L)
            {
                var SupplierId = ed_Supplier.Value.ToLong();
                var SupplierEntity = SupplierContract.GetById(SupplierId);
                if (SupplierEntity != null)
                {
                    if (SupplierEntity.AccountPeriod > 0)
                    {
                        ed_PaymentDays.SetValue(SupplierEntity.AccountPeriod);
                        ed_AppointPayDate.SetValue(DateTime.Now.AddDays(SupplierEntity.AccountPeriod).TimeToStringDate());
                    }
                }
            }
            else
            {
                ed_PaymentDays.SetValue("30");
                ed_AppointPayDate.SetValue(DateTime.Now.AddDays(30).TimeToStringDate());
            }
        }

        protected void ed_PaymentDays_TextChanged(object sender, EventArgs e)
        {
            var PayMentDays = ed_PaymentDays.GetValue().ToInt();
            ed_AppointPayDate.SetValue(DateTime.Now.AddDays(PayMentDays).TimeToStringDate());
        }
    }
}
